package com.xinyu.controller;

import com.xinyu.config.FileStorageProperties;
import com.xinyu.domain.User;
import com.xinyu.service.IUserService;
import com.xinyu.utils.FileUploadUtil;
import com.xinyu.utils.JWTUtils;
import com.xinyu.vo.AttachmentFileInfo;
import com.xinyu.vo.BaseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Value("${file.upload.directory}")
    private String uploadDir; // 上传文件的根目录

    @Autowired
    private FileStorageProperties fileStorageProperties;

    @Autowired
    private IUserService userService;

    @Autowired
    private HttpServletRequest request;

    private static final long MAX_FILE_SIZE = 10L * 1024 * 1024; // 10MB

    private static final Set<String> ALLOWED_IMAGE_TYPES = Collections.unmodifiableSet(
            new HashSet<>(Arrays.asList(
                    "image/jpeg",
                    "image/png",
                    "image/gif",
                    "image/webp"
            ))
    );

    @PostMapping
    public ResponseEntity<BaseResult> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (file == null || file.isEmpty()) {
                return ResponseEntity.ok(BaseResult.error("文件不能为空"));
            }

            String authorization = request.getHeader("Authorization");
            if (StringUtils.isBlank(authorization)) {
                return ResponseEntity.ok(BaseResult.error("未登录"));
            }

            Integer userId = JWTUtils.getUserIdFromToken(authorization);
            if (userId == null) {
                return ResponseEntity.ok(BaseResult.error("未登录"));
            }
            User operator = userService.getById(userId);
            if (operator == null) {
                return ResponseEntity.ok(BaseResult.error("账号不存在"));
            }

            if (file.getSize() > MAX_FILE_SIZE) {
                return ResponseEntity.ok(BaseResult.error("文件不能超过10MB"));
            }

            String contentType = determineContentType(file);
            if (StringUtils.isNotBlank(contentType) && contentType.startsWith("image/")
                    && !ALLOWED_IMAGE_TYPES.contains(contentType.toLowerCase())) {
                return ResponseEntity.ok(BaseResult.error("不支持的图片格式"));
            }

            AttachmentFileInfo storedInfo = FileUploadUtil.saveFile(file, uploadDir);
            AttachmentFileInfo responseInfo = new AttachmentFileInfo(
                    fileStorageProperties.getBaseUrl() + storedInfo.getFilePath(),
                    storedInfo.getFileName(),
                    storedInfo.getFileSize(),
                    contentType
            );

            return ResponseEntity.ok(BaseResult.ok(responseInfo));
        } catch (IOException e) {
            return ResponseEntity.ok(BaseResult.error("文件上传失败"));
        }
    }

    private String determineContentType(MultipartFile file) {
        if (file == null) {
            return null;
        }
        String contentType = file.getContentType();
        return contentType == null ? null : contentType.toLowerCase();
    }
}
